/**
 * 收藏相关接口
 */

import { getApiBaseUrl } from "@/utils/env";
import { getStorage } from "@/utils/storage";

const BASE_URL = getApiBaseUrl();

// 获取用户ID（从登录状态获取）
function getUserId() {
  // 从登录状态获取用户ID
  const userId = getStorage('user_id');
  
  if (!userId) {
    throw new Error('请先登录');
  }
  
  return userId;
}

// 获取 token
function getToken() {
  const token = getStorage('user_token');
  return token || '';
}

/**
 * 添加收藏
 * @param {number} imageId 图片ID
 * @returns {Promise}
 */
export function addFavorite(imageId) {
  return new Promise((resolve, reject) => {
    try {
      const userId = getUserId();
      const token = getToken();
      
      uni.request({
        url: `${BASE_URL}/api/favorites`,
        method: "POST",
        header: {
          'Authorization': `Bearer ${token}`,
          'X-User-Id': userId
        },
        data: {
          imageId: imageId,
          userId: userId
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const response = res.data;
            
            // 兼容两种格式
            if (response && typeof response === 'object' && response.code === 200 && response.data) {
              resolve(response.data);
            } else if (response && typeof response === 'object') {
              resolve(response);
            } else {
              resolve({ success: true });
            }
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
}

/**
 * 取消收藏
 * @param {number} imageId 图片ID
 * @returns {Promise}
 */
export function removeFavorite(imageId) {
  return new Promise((resolve, reject) => {
    try {
      const userId = getUserId();
      const token = getToken();
      
      uni.request({
        url: `${BASE_URL}/api/favorites/${imageId}`,
        method: "DELETE",
        header: {
          'Authorization': `Bearer ${token}`,
          'X-User-Id': userId
        },
        data: {
          userId: userId
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const response = res.data;
            
            // 兼容两种格式
            if (response && typeof response === 'object' && response.code === 200 && response.data) {
              resolve(response.data);
            } else if (response && typeof response === 'object') {
              resolve(response);
            } else {
              resolve({ success: true });
            }
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
}

/**
 * 检查是否已收藏
 * @param {number} imageId 图片ID
 * @returns {Promise<boolean>}
 */
export function checkFavorite(imageId) {
  return new Promise((resolve, reject) => {
    try {
      const userId = getUserId();
      const token = getToken();
      
      uni.request({
        url: `${BASE_URL}/api/favorites/check/${imageId}`,
        method: "GET",
        header: {
          'Authorization': `Bearer ${token}`,
          'X-User-Id': userId
        },
        data: {
          userId: userId
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const response = res.data;
            
            // 兼容两种格式
            if (response && typeof response === 'object' && response.code === 200 && response.data) {
              resolve(response.data.isFavorite || false);
            } else if (response && typeof response === 'object' && response.isFavorite !== undefined) {
              resolve(response.isFavorite);
            } else {
              resolve(false);
            }
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
}

/**
 * 获取用户收藏列表
 * @param {Object} params 请求参数
 * @param {number} params.page 页码
 * @param {number} params.pageSize 每页数量
 * @returns {Promise}
 */
export function getFavoriteList(params = {}) {
  return new Promise((resolve, reject) => {
    try {
      const userId = getUserId();
      const token = getToken();
      
      uni.request({
        url: `${BASE_URL}/api/favorites`,
        method: "GET",
        header: {
          'Authorization': `Bearer ${token}`,
          'X-User-Id': userId
        },
        data: {
          page: params.page || 1,
          pageSize: params.pageSize || 20,
          userId: userId
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const response = res.data;
            
            // 兼容两种格式
            if (response && typeof response === 'object' && response.code === 200 && response.data) {
              resolve({
                code: 200,
                data: response.data
              });
            } else if (response && typeof response === 'object' && response.list !== undefined) {
              resolve({
                code: 200,
                data: response
              });
            } else {
              resolve({
                code: 200,
                data: response
              });
            }
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
}

/**
 * 批量检查收藏状态
 * @param {Array<number>} imageIds 图片ID数组
 * @returns {Promise<Set<number>>}
 */
export function batchCheckFavorites(imageIds) {
  return new Promise((resolve, reject) => {
    try {
      const userId = getUserId();
      const token = getToken();
      
      uni.request({
        url: `${BASE_URL}/api/favorites/batch-check`,
        method: "POST",
        header: {
          'Authorization': `Bearer ${token}`,
          'X-User-Id': userId
        },
        data: {
          imageIds: imageIds,
          userId: userId
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const response = res.data;
            
            // 兼容两种格式
            let favorites = [];
            if (response && typeof response === 'object' && response.code === 200 && response.data) {
              favorites = response.data.favorites || [];
            } else if (response && typeof response === 'object' && response.favorites) {
              favorites = response.favorites;
            }
            
            resolve(new Set(favorites));
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    } catch (err) {
      reject(err);
    }
  });
}
